package com.liu.stockmarket.ui.detail

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DividerItemDecoration
import com.liu.stockmarket.BaseActivity
import com.liu.stockmarket.R
import com.liu.stockmarket.StockMarketApplication
import com.liu.stockmarket.databinding.ActivityDetailBinding
import com.liu.stockmarket.databinding.HeaderStockDetailBinding
import com.liu.stockmarket.model.ResponseResult
import com.liu.stockmarket.model.StockDetailAndProfit
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.ui.kline.KlineActivity
import com.liu.stockmarket.ui.search.SearchResultAdapter
import com.liu.stockmarket.ui.stock.add.StockAddActivity
import com.liu.stockmarket.utils.*
import java.math.BigDecimal

class DetailActivity : BaseActivity() {
    private lateinit var binging: ActivityDetailBinding

    private lateinit var headerStockDetailBinding: HeaderStockDetailBinding

    private lateinit var mAdapter: DetailAdapter

    private lateinit var viewModel: DetailViewModel

    private var stockId: Long = -1

    private lateinit var stock: StockEntity

    override fun initView(savedInstanceState: Bundle?) {
        binging = ActivityDetailBinding.inflate(layoutInflater)
        headerStockDetailBinding = HeaderStockDetailBinding.inflate(layoutInflater)
        setContentView(binging.root)
        setToolbar(binging.toolbar.toolbar, true)
        title = "交易信息"

        intent.extras?.let {
            stockId = it.getLong(STOCK_ID_KEY)
        }

        val stockMarketApplication = this.application as StockMarketApplication
        viewModel = ViewModelProvider(
            this, DetailViewModel.DetailViewModelFactory(
                stockMarketApplication.transactionRecordRepository,
                stockMarketApplication.stockRepository,
                stockMarketApplication.easyMoneyRepository, stockId
            )
        ).get(DetailViewModel::class.java)


//        binging.parent.addView(headerStockDetailBinding.root.rootView, 0)

        mAdapter = DetailAdapter()

        mAdapter.addHeaderView(headerStockDetailBinding.root,0)


        with(binging.list) {
            this.adapter = mAdapter
            this.addItemDecoration(
                DividerItemDecoration(
                    this@DetailActivity,
                    DividerItemDecoration.VERTICAL
                )
            )

        }


    }

    override fun listener() {
        setToolbarButton("走势") {
            KlineActivity.start(
                this,
                stock.code.getKlineCode(stockType = stock.stockType, stock.transactionExchange),
                stock.name,
                stock.transactionExchange.getKlineType()
            )
        }

        binging.fabAdd.setOnClickListener {
            StockAddActivity.start(
                this,
                SearchResultAdapter.Item(
                    id = stock.id,
                    code = stock.code,
                    name = stock.name,
                    type = "",
                    stockType = stock.stockType,
                    transactionExchange = stock.transactionExchange
                )
            )
        }

    }

    override fun observer() {
        viewModel.allTransactionRecords.observe(this) {
            viewModel.parse(it)
        }
        viewModel.result.observe(this) {
            if (it.isSuccess()) {
                if (it.data == null || it.data.details.isNullOrEmpty()) {
                    mAdapter.setList(mutableListOf())
                    emptyViewBinding.tvText.text = "没有交易数据"
                    mAdapter.setEmptyView(emptyViewBinding.root)

                } else {
                    mAdapter.setList(it.data.details)

                }

                setHeader(it)
            } else {
                finish()
            }
        }
        viewModel.stock.observe(this) {
            stock = it
            title = it.name
            setSubTitle(it.code)
        }
    }

    private fun setHeader(responseResult: ResponseResult<StockDetailAndProfit>) {
        responseResult.data?.let {
            with(headerStockDetailBinding) {
                if (it.profit.holdingMoney == BigDecimal.ZERO) {
                    // 清空的股票不显示收益率
                    tvTodayProfitPercent.visibility = View.GONE
                    tvAccumulativeProfitPercent.visibility = View.GONE
                }

                tvAllHoldingMoney.text = it.profit.holdingMoney.getString()
                tvTodayProfit.money(context = this@DetailActivity, it.profit.todayProfit)
                tvTodayProfitPercent.percent(
                    context = this@DetailActivity,
                    it.profit.todayProfitPercent
                )
                tvAccumulativeProfit.money(context = this@DetailActivity, it.profit.allProfit)
                tvAccumulativeProfitPercent.percent(
                    context = this@DetailActivity,
                    it.profit.allProfitPercent
                )
                tvTransactionNumber.text = it.transactionCount.toString()
                tvTransactionAllHandlingFee.text = it.handlingFee.getString()
            }
        }
    }


    companion object {
        const val STOCK_ID_KEY = "stock_id"
        fun start(context: Context, stockId: Long) {
            context.start(
                bundle = bundleOf(
                    STOCK_ID_KEY to stockId
                ), DetailActivity::class.java
            )
        }
    }

}